﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DHLAppMovil.Properties;
using System.IO;
using Db4objects.Db4o;
using System.Reflection;
using OpenNETCF.Desktop.Communication;
using BE;


namespace DHLAppMovil
{
    public partial class Form1 : Form
    {
        public static Form1 form1Temp;
        BackgroundWorker backgroundWorker1;
        string ruta=Settings.Default.Ruta;
        public Form1()
        {
            InitializeComponent();
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            form1Temp = this;
            backgroundWorker1 = new BackgroundWorker();
            backgroundWorker1.WorkerReportsProgress = true;
            // This event will be raised on the worker thread when the worker starts
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            // This event will be raised when we call ReportProgress
            backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
            //backgroundWorker1.RunWorkerAsync();
            string pathBD = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\bd.db4o";
            using (IObjectContainer db = Db4oEmbedded.OpenFile(pathBD))
            {
                Class1 clase = new Class1(null);
                IObjectSet result2 = db.QueryByExample(clase);

                if (result2.Count > 0)
                {
                    string nohaynada = "nada";
                }
            }
        }

        void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            


            var bd = new DHLDataContextDataContext();
            List<TB_M_PERSONA> listaPersona = (from c in bd.TB_M_PERSONAs
                                               select c).ToList();
            List<Persona> listaPersonasDB4o = new List<Persona>();


            foreach (var p in listaPersona)
            {
                Persona persona = new Persona();
                persona.Cargo = p.NAMLUGAR;
                persona.Codigo = p.CODIGOTAGSTR;
                persona.Condicion = p.N_EST_PERSONA;
                persona.Imagen = ReadFile(p.FOTO);
                persona.Nombre = p.C_PRI_NOMBRE + " " + p.C_APE_PATERNO + " " + p.C_APE_MATERNO;
                persona.CodigoInt = (int)p.CODIGOTAG;
                listaPersonasDB4o.Add(persona);
            }
            backgroundWorker1.ReportProgress(10);

            //Donde esta el lugar del ejecutable
            string pathBD = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\bd.db4o";

            using (RAPI rapi = new RAPI())
            {
                //Si existe la bd hay que borrarlo
                if (File.Exists(pathBD))
                {
                    File.Delete(pathBD);
                }

                rapi.Connect(true);
                if (rapi.DeviceFileExists(@ruta) == true)
                {
                    rapi.CopyFileFromDevice(pathBD, @ruta);
                    rapi.Disconnect();

                    //Proceder a la copia
                }

            }

            backgroundWorker1.ReportProgress(30);

            using (IObjectContainer db = Db4oEmbedded.OpenFile(pathBD))
            {
                // do something with db4o
                try
                {
                    //Primero vamos a sincronizar la data
                    BE.Class1 clase = new Class1(null);
                    clase.Caso = "prueba";
                    db.Store(clase);
                    db.Commit();

                    //Vamos a buscar a todos para borrarlos:
                    //Persona persona = new Persona();
                    //IObjectSet result = db.QueryByExample(persona);
                    //List<Persona> listaPersonas = new List<Persona>();
                    //foreach (var c in result)
                    //{
                    //    db.Delete((Persona)c);
                    //}
                    //db.Commit();
                    //progressBar1.Value = 30;
                    backgroundWorker1.ReportProgress(40);
                    foreach (var c in listaPersonasDB4o)
                    {
                        //db.Store(c);
                    }
                    db.Commit();
                    db.Close();
                    backgroundWorker1.ReportProgress(50);
                    using (RAPI rapi = new RAPI())
                    {

                        rapi.Connect(true);
                        if (rapi.DeviceFileExists(@ruta) == false)
                        {
                            rapi.CopyFileToDevice(pathBD, @ruta);
                            rapi.Disconnect();
                        }
                        else
                        {
                            rapi.DeleteDeviceFile(@ruta);
                            rapi.CopyFileToDevice(pathBD, @ruta);
                            rapi.Disconnect();
                        }


                    }
                    backgroundWorker1.ReportProgress(100);

                    MessageBox.Show("El proceso termino exitosamente");
                }
                catch (Exception exc)
                {
                    MessageBox.Show("Error: " + exc.Message);
                }
            }
        }
        // Back on the 'UI' thread so we can update the progress bar
        void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.BeginInvoke(
            new Action(() =>
            {
                progressBar1.Value = e.ProgressPercentage;
            }
            ));
            
        }

        private delegate void ProcessDelegate();

        private void button1_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
            
        }

            public byte[] ReadFile(string sPath)
            {

              byte[] data = null;    

              FileInfo fInfo = new FileInfo(sPath); 
              long numBytes = fInfo.Length;   

              FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);  

              BinaryReader br = new BinaryReader(fStream);  

              data = br.ReadBytes((int)numBytes);  
              
              return data;  
            }

            private void button2_Click(object sender, EventArgs e)
            {
                // retrieveAllPilotQBE
                string pathBD=Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

                using (IObjectContainer db = Db4oEmbedded.OpenFile(pathBD + "\\bd.db4o"))
                {
                    // do something with db4o
                    try
                    {
                        Persona persona = new Persona();
                        IObjectSet result = db.QueryByExample(persona);
                        List<Persona> listaPersonas = new List<Persona>();
                        foreach(var c in result)
                        {
                            listaPersonas.Add((Persona)c);
                        }
                    }
                    catch (Exception exc)
                    {
                    }
                }


                
            }
 
    }
}
